package com.tcl.aota.web.controller;

import com.tcl.aota.common.constants.Constants;
import com.tcl.aota.manage.StrategyManage;
import com.tcl.aota.persistent.model.Strategy;
import com.tcl.aota.web.manage.AppCheckManage;
import com.tcl.aota.web.vo.AppLogVo;
import com.tcl.aota.web.vo.AppVo;
import com.tcl.aota.web.vo.JsonResult;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author xiaolong.hou
 * @version 1.0.0
 * @decs API for client
 * @date 2013-10-21
 */

@Controller
public class AppCheckController {

    private final static Logger logger = Logger.getLogger(AppCheckController.class);

    @Resource
    private StrategyManage strategyManage;

    @Resource
    private AppCheckManage appCheckManage;

    /**
     * 功能： 客户端获取APPS接口
     * tips: 服务器根据什么条件返回APPS？
     */
    @ResponseBody
    @RequestMapping(value = "/app/checkList", method = RequestMethod.GET)
    public JsonResult appList(String appCu, String appOs) {
        if (StringUtils.isEmpty(appCu) || "Unknown".equals(appCu)) {
            logger.info("Param Error,appCu:" + appCu);
            return JsonResult.get(Constants.Common.PARAMS_INVALID, null);
        }
        if (StringUtils.isEmpty(appOs)) {
            logger.info("Param Error,appOs:" + appOs);
            return JsonResult.get(Constants.Common.PARAMS_INVALID, null);
        }
        //cu过滤掉第2个中划线后的数据
        int firstIndex = appCu.indexOf("-");
        int secondIndex = appCu.indexOf("-", firstIndex + 1);
        if (secondIndex != -1) {
            appCu = appCu.substring(0, secondIndex);
        }
        return JsonResult.get(Constants.Common.SUCCESS, appCheckManage.selectAppListByLatestPkg(appCu, appOs));
    }

    /**
     * app详情
     *
     * @param appId：appId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/app/appDetail/{appId}", method = RequestMethod.GET)
    public AppVo appDetail(@PathVariable Long appId) {
        return appCheckManage.selectById(appId);
    }


    /**
     * app更新策略
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/app/strategy", method = RequestMethod.GET)
    public Strategy getStrategy() {
        return strategyManage.selectStrategy();
    }


    /**
     * 上传app下载安装成功失败日志
     *
     * @param appLogList
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/app/applog", method = RequestMethod.POST)
    public int appLog(@RequestBody List<AppLogVo> appLogList) {
        return appCheckManage.insertAppLog(appLogList);
    }
}
